clc;
clear all;
close all;

%% INIT
N = 4; k = 1; r = 5; p = 4;
lower = 0.0;
upper = 0.9999999999999;
step = 2^(-N);
ulp = 2^(-p);

out_file = 'data_err_prob.csv';
fid = fopen(out_file, 'w');

%% SIMULATION

%print header
fprintf(fid, 'n = %d,',N);
fprintf(fid, 'k = %d,',k);
fprintf(fid, 'r = %d,',r);
fprintf(fid, 'p = %d,',p);
fprintf(fid, '\n');

fprintf(fid, 'Num,');
for i = 1:N
    fprintf(fid, 'a%u,',(N-i));
end
fprintf(fid,' ,');
for i = 1:N
    fprintf(fid, 'b%u,', (N-i));
end
fprintf(fid,' ,');
fprintf(fid, '#1s/truncated,');
fprintf(fid, 'Sum(truncated,');
fprintf(fid, 'E_{reduct},');
fprintf(fid, 'E_{round},');
fprintf(fid, 'E_{total},');
fprintf(fid, 'E_{total_orig},');
fprintf(fid, '\n');

%print rows
index = 0;
[err_total,err_red, err_rnd] = ccm_const(N, N, r, k);
err_total = err_red + err_rnd;
for a = lower:step:upper
    for b = lower:step:upper
        index = index + 1;
        ans_true = a * b;
        
        astr = bin2str(a, 0, N);
        bstr = bin2str(b, 0, N);
        
        col_trunc = 2 * N - r - k;
        num_trunc = (col_trunc * (col_trunc + 1))/2;
        num_one = 0;
        for bi = 0:col_trunc
            for ai = 0:col_trunc
                if ((ai+bi) < col_trunc) && (astr(N-ai) == '1') && (bstr(N-bi) == '1')
                    num_one = num_one + 1;
                end
            end
        end
        num_one_ratio = double(num_one/num_trunc);
        [z,s] = trunc_mult(a, b, 0.0, N, N, r, k);
        sum_trunc = ans_true - s;
        err_total_com = ans_true - z;
        
        
        fprintf(fid, '%d,', index);
        for i = 1:N
            fprintf(fid, '%s,',astr(i));
        end
        fprintf(fid, ' ,');
        for i = 1:N
            fprintf(fid, '%s,',bstr(i));
        end
        fprintf(fid, ' ,');
        fprintf(fid, '%f,',num_one_ratio);
        fprintf(fid, '%f,',sum_trunc);
        fprintf(fid, '%f,', err_red);
        fprintf(fid, '%f,', err_rnd);
        fprintf(fid, '%f,', err_total_com);
        fprintf(fid, '%f,', err_total);
        fprintf(fid, '\n');        
    end
end

fclose(fid);





